#!/usr/bin/env python

import time
import resource.string.app

from .._console import Console
from .._config import Config

class Voucher(Console):

    def run(self):
        self.greeting(resource.string.app)
        
        command = self.loadCommand()
        if command:
            modem = self.loadModem()
            if modem:
                self.cusd(modem, command)
        
        self.farewell()

    def loadCommand(self):
        self.progress('Read voucher command... ')
        config = Config()
        try:
            command = config.get('SMS', 'voucher')
        except:
            command = None
            self.fail('Error >_<\n')
            self.fail('Voucher setting not found.\n')
            self.fail('Please create [SMS] voucher entry in the setting.\n')
        else:
            self.success('OK ^_^v\n')
            self.verbose('Voucher command: %s\n' % command)
            
        return command
    
    def loadModem(self):
        self.progress('Opening modem... ')
        modem = super(Voucher, self).loadModem()
        if modem: self.success('OK ^_^v\n')
        else: self.fail('Error >_<\n')
        return modem
    
    def cusd(self, modem, command):
        self.progress('Querying for voucher balance... ')
        result = modem.at('+CSCS="GSM"', 20)
        ok = 'OK' in result
        if ok:
            result = modem.cusd(command)
        if result:
            self.success('OK ^_^v\n\n')
        else:
            self.fail('Error >_<\n')
        self.info('%s\n' % result)
        